<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
/**
 *
 * functions.php template file
 *
 * (c) 2009 by Mike Walsh
 *
 * @author Mike Walsh <mike@walshcrew.com>
 * @package casl-soccer
 * @subpackage options
 * @version $Revision$
 * @lastmodified $Author$
 * @lastmodifiedby $Date$
 *
 */

require_once('theme-options.inc.php') ;

/**
 * Register the form setting for our casl_theme_options array.
 *
 * This function is attached to the admin_init action hook.
 *
 * This call to register_setting() registers a validation callback,
 * casl_theme_options_validate(), which is used when the option is
 * saved, to ensure that our option values are complete, properly
 * formatted, and safe.
 *
 * We also use this function to add our theme option if it doesn't already exist.
 *
 * Note:  Code adapted from the Twenty Eleven theme.
 *
 * @since CASL 1.0
 */
function casl_theme_options_init()
{
	// If there are no options in the database, add them now.

	register_setting(
		'casl_theme_options',       // Options group, see settings_fields() call in theme_options_render_page()
		'casl_theme_options', // Database option, see casl_get_theme_options()
		'casl_theme_options_validate' // The sanitization callback, see casl_theme_options_validate()
	) ;

	//if (false === casl_get_theme_options())
	add_option('casl_theme_options', casl_get_default_theme_options()) ;
}
add_action('admin_init', 'casl_theme_options_init') ;

/**
 * Enqueue any external libraries and CSS needed to support admin options.
 *
 * @return - void
 */
function casl_theme_enqueue_admin()
{
    //  Load jQuery UI Accordion

    //  The jQuery accordion function is not shipped with WordPress so
    //  we need to load it from the Goolge CDN.  Since we're going to load
    //  the jQuery Accordion, we'll load the rest of the jQuery modules we
    //  need from the Google CDN as well to make sure they are all compatible.

    //  This really needs to be limited to just the Theme Options page but for now ...

    wp_deregister_script('jquery', 'jquery-ui-core', 'jquery-ui-accordion');
    wp_register_script('jquery',
        'https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js', array(), false, false);
    wp_register_script('jquery-ui',
        'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js', array('jquery'), false, true);
    wp_enqueue_script('jquery');
    wp_enqueue_script('jquery-ui');
    wp_enqueue_script('jquery-ui-core');
    wp_enqueue_script('jquery-ui-accordion');
    wp_enqueue_style('accordion-css', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css') ; 
    
}

add_action('admin_init', 'casl_theme_enqueue_admin') ;

/**
 * Enqueue any external libraries and CSS needed to support theme.
 *
 * @return - void
 */
function casl_theme_enqueue_styles()
{
    //  Load the CSS based on the theme options

    $theme_url = get_stylesheet_directory_uri() ;

    $theme_options = casl_get_theme_options() ;
    $color = $theme_options[CASL_THEME_OPTION_LLI] ;

    //  If the "Chelsea" logo is being used, load the blue scheme, red for all others.
    $color = (strtolower($theme_options[CASL_THEME_OPTION_LLI])
        == strtolower(CASL_THEME_LEAGUE_LOGO_CHELSEA)) ? 'blue' : 'red' ;

    $color_scheme_css = sprintf("%s/css/%s.css", $theme_url, strtolower($color)) ;

    wp_register_style('casl-color-css', $color_scheme_css) ; 
    wp_enqueue_style('casl-color-css') ;
}

//  Hook in a redirect action for the template to the enqueue will run

add_action('print_styles','casl_theme_enqueue_styles');

/**
 * filter to add a theme footer
 *
 */
function casl_theme_footer()
{
    $txt = sprintf('Copyright &copy; 2009-%s, %s - All rights reserved.<br>',
        date('Y'), get_bloginfo('name')) ;
    $txt .= '<span id="casl-link">Capital Area Soccer League | 3300 Woman\'s Club Drive, Suite 1, Raleigh NC 27612 | phone 919.834.3951 | fax 919.834.4369</span><br/>' ;

    $txt .= 'The <a href="http://www.michaelwalsh.org/wordpress-themes/casl-soccer-theme/" title="CASL-Soccer">CASL-Soccer</a> theme (vMAJOR_RELEASE.MINOR_RELEASE.$WCREV$) is powered by <a rel="generator" title="Semantic Personal Publishing Platform" href="http://wordpress.org/">WordPress</a> and the <a href="http://www.themeshaper.com/thematic">Thematic</a> theme framework.' ;

    return $txt ;
}



//  Hook in a action for the template to the enqueue will run

add_action('thematic_footertext', 'casl_theme_footer');

//  Set up theme options - allows theme
//  to be configured with a color scheme
//  and Fibblesnork background images.

add_action('admin_menu', 'casl_theme_options_page');

/**
 * School Sports Theme options page hook
 *
 */
function casl_theme_options_page()
{
    $casl_theme_options_page = add_theme_page('casl',
        'CASL Soccer Options', 'edit_themes', basename(__FILE__), 'casl_theme_set_options');

    if ($casl_theme_options_page)
        add_contextual_help($casl_theme_options_page, casl_theme_options_contextual_help()) ;
}

/**
 * casl_theme_options_contextual_help()
 *
 * Build contextual help to be displayed when on the theme options page.
 *
 * @return sting - contextual help.
 */
function casl_theme_options_contextual_help()
{
    $ch = '<h2>CASL Soccer Theme</h2>' ;
    $ch .= '<p>Choose the desired league and optionally add one to three images to the' ;
    $ch .= 'header using the Drag and Drop Media Library.  You can upload an image to the' ;
    $ch .= 'Media Library for it to be available.  If you know CSS, you can tweak the ' ;
    $ch .= 'appearance of the header to meet your needs.' ;

    return $ch ;
}

/**
 * Build Header Image Drag and Drop
 *
 * @param $filler - string - filler to add to ids and classes.
 */
function casl_header_image_drag_n_drop($filler)
{
    $theme_options = casl_get_theme_options() ;
    //print_r($theme_options) ;

    $thumbnail_width = get_option('thumbnail_size_w') * $theme_options[CASL_THEME_OPTION_THUMBNAIL_SCALE_FACTOR] ;
    $thumbnail_height = get_option('thumbnail_size_h') * $theme_options[CASL_THEME_OPTION_THUMBNAIL_SCALE_FACTOR] ;
 
    //  Build the drag zone - don't include the existing image if set

    printf("<div class=\"demo ui-widget ui-helper-clearfix\">\n") ;

    printf("<ul id=\"casl%shdrgallery\" class=\"gallery ui-helper-reset ui-helper-clearfix\">\n", $filler) ;

    //  Need to get all of the images in the Media library
    //$images2 = &get_children('post_type=attachment&post_mime_type=image') ;
    
    $query_images_args = array(
        'post_type' => 'attachment'
       ,'post_mime_type' =>'image'
       ,'post_status' => 'inherit'
       ,'posts_per_page' => -1
    ) ;

    $images = array() ;
    $query_images = new WP_Query($query_images_args) ;

    foreach ($query_images->posts as $image)
    {
        $images[]= $image->ID ;
    }
    
    //  Loop over images and figure out thumbnails and full size images.
    //  Use of the PHP_EOL constant isn't necessary but does make the HTML
    //  easier to read and debug.

    foreach ($images as $attachment_id)
    {
        $thumb = wp_get_attachment_image_src($attachment_id, 'thumb', false) ;
        $image = wp_get_attachment_image_src($attachment_id, 'full', false) ;

        printf('<li id="casl%shdrimg-%s" class="ui-widget-content ui-corner-tr">%s', $filler, $attachment_id, PHP_EOL) ;
        printf('<h5 class="ui-widget-header">%sx%s</h5>%s', $image[1], $image[2], PHP_EOL) ;
        printf('<img src="%s" width="%s" height="%s" alt="%s"/>%s', $thumb[0], $thumbnail_width, $thumbnail_height, basename($image[0]), PHP_EOL) ;
   
        printf('<a href="%s" title="%s" class="ui-icon ui-icon-zoomin">View Larger</a>%s', $image[0], basename($image[0]), PHP_EOL) ;
        printf('<a href="%s" title="Select Image" class="ui-icon ui-icon-check">Remove Image</a>%s</li>%s', $image[0], PHP_EOL, PHP_EOL) ;
    }

    //  Build the drop zone and handle exisitng image if set

    printf('</ul>%s<div id="casl%shdrimg" class="ui-widget-content ui-state-default">%s', PHP_EOL, $filler, PHP_EOL) ;
    printf('<h4 class="ui-widget-header"><span class="ui-icon ui-icon-check">Header Image</span>Image</h4>%s</div>%s', PHP_EOL, PHP_EOL);
    printf('</div><!-- End DnD block -->%s', PHP_EOL) ;
}

/**
 * casl theme options page form
 *
 */
function casl_theme_set_options()
{
    $theme_options = casl_get_theme_options() ;

    $casl_theme_logo_options = array(
        CASL_THEME_LEAGUE_LOGO_CASL => CASL_THEME_LEAGUE_LOGO_CASL
       ,CASL_THEME_LEAGUE_LOGO_RECREATIONAL => CASL_THEME_LEAGUE_LOGO_RECREATIONAL
       ,CASL_THEME_LEAGUE_LOGO_CHALLENGE => CASL_THEME_LEAGUE_LOGO_CHALLENGE
       ,CASL_THEME_LEAGUE_LOGO_CLASSIC => CASL_THEME_LEAGUE_LOGO_CLASSIC
       ,CASL_THEME_LEAGUE_LOGO_YTS => CASL_THEME_LEAGUE_LOGO_YTS
       ,CASL_THEME_LEAGUE_LOGO_AMBASSADORS => CASL_THEME_LEAGUE_LOGO_AMBASSADORS
       ,CASL_THEME_LEAGUE_LOGO_CHELSEA => CASL_THEME_LEAGUE_LOGO_CHELSEA
       ,CASL_THEME_LEAGUE_LOGO_NONE => CASL_THEME_LEAGUE_LOGO_NONE
    ) ;

    $casl_theme_thumbnails = array() ;
    $url = dirname(get_bloginfo('stylesheet_url')) ;
    
    foreach ($casl_theme_logo_options as $logo)
    {
        $img = sprintf("%s/images/CASL/%s", $url,
            sprintf(CASL_THEME_LEAGUE_LOGO_IMAGE, $logo)) ;
        $key = sprintf("%s", ucwords($logo)) ;
        $casl_theme_thumbnails[$key] = $img ;
    }

    //  Default thumbnails are big, add a scaling factor which
    //  will become an theme option setting in the future.

    $thumbnail_width = get_option('thumbnail_size_w') * $theme_options[CASL_THEME_OPTION_THUMBNAIL_SCALE_FACTOR] ;
    $thumbnail_height = get_option('thumbnail_size_h') * $theme_options[CASL_THEME_OPTION_THUMBNAIL_SCALE_FACTOR] ;

?>
<div class="wrap">
<?php screen_icon(); ?>
<h2><?php printf( __( '%s Theme Options', 'casl' ), get_current_theme() ); ?></h2>
<?php settings_errors(); ?>
<style type="text/css">
/* Drag and Drop */
#droppable, #header-image-left, #header-image-center, #header-image-right { width: 150px; height: 150px; padding: 0.5em; float: left; margin: 10px; }
.draggable-image, #draggable, #draggable-nonvalid { width: 100px; height: 100px; padding: 0.5em; float: left; margin: 10px 10px 10px 0; }

/* Gallery Control */
.gallery.custom-state-active { background: #eee; }
.gallery li { float: left; width: <?php echo $thumbnail_width . "px"?>; padding: 0.4em; margin: 0 0.4em 0.4em 0; text-align: center; }
.gallery li h5 { margin: 0 0 0.4em; cursor: move; }
.gallery li a { float: right; }
.gallery li a.ui-icon-zoomin { float: left; }
.gallery li img { width: 100%; cursor: move; }

/* Left Header Image */
#casllfthdrgallery { float: left; width: 75%; min-height: 12em; } * html #casllfthdrgallery { height: 12em; } /* IE6 */
#casllfthdrimg { float: right; width: 20%; min-height: 12em; padding: 1%; text-align: center; margin: 0 auto;} * html #casllfthdrimg { height: 18em; } /* IE6 */
#casllfthdrimg h4 { line-height: 20px; margin: 0 0 0.4em; }
#casllfthdrimg h4 .ui-icon { float: left; }
#casllfthdrimg .gallery h5 { display: none; }

/* Center Header Image */
#caslctrhdrgallery { float: left; width: 75%; min-height: 12em; } * html #caslctrhdrgallery { height: 12em; } /* IE6 */
#caslctrhdrimg { float: right; width: 20%; min-height: 15em; padding: 1%;} * html #caslctrhdrimg { height: 18em; } /* IE6 */
#caslctrhdrimg h4 { line-height: 16px; margin: 0 0 0.4em; }
#caslctrhdrimg h4 .ui-icon { float: left; }
#caslctrhdrimg .gallery h5 { display: none; }

/* Right Header Image */
#caslrghthdrgallery { float: left; width: 75%; min-height: 12em; } * html #caslrghthdrgallery { height: 12em; } /* IE6 */
#caslrghthdrimg { float: right; width: 20%; min-height: 15em; padding: 1%;} * html #caslrghthdrimg { height: 18em; } /* IE6 */
#caslrghthdrimg h4 { line-height: 16px; margin: 0 0 0.4em; }
#caslrghthdrimg h4 .ui-icon { float: left; }
#caslrghthdrimg .gallery h5 { display: none; }

</style>

<br clear="all"/>

    <form name="casl_theme_options" method="post" action="options.php">
			<?php
				settings_fields('casl_theme_options') ;
				$theme_options = casl_get_theme_options() ;
            ?>
    <div id="options-accordion">
        <div><h3><a href="#">CASL League Logo</a></h3>
            <div>
                <table class="widefat fixed" style="margin: 10px 0px;" cellspacing="0">
                <tbody id="the-list" class="list:post">
<?php
    $tdctr = 0 ;
    $priorSize = null ;

    foreach ($casl_theme_thumbnails as $key => $value)
    {
        //var_dump(strtolower($key) === $theme_options[CASL_THEME_OPTION_LLI]) ;
        $checked = (strtolower($key) == $theme_options[CASL_THEME_OPTION_LLI]) ? " checked=\"checked\"" : "" ;

        list($size, $color) = explode(":", $key) ;

        //  New row?  If so, open the row.
        if ($tdctr == 0)
            print '<tr valign="middle">' . PHP_EOL ;

        printf("<td style=\"padding: 10px 5px;\" align=\"center\"><img src=\"%s\" alt=\"%s\"><br/>", $value, basename($value)) ;
        printf("<input type='radio' name='%s' value=\"%s\"%s /><br/>",
            'casl_theme_options[' . CASL_THEME_OPTION_LLI . ']', strtolower($key), $checked) ;
        printf("<strong>%s<br/>%s</strong></td>", $size, $color) ;
        print PHP_EOL ;

        //  End the row after 2 columns
        if (++$tdctr == 2)
        {
            $tdctr = 0 ;
            print '</tr>' . PHP_EOL ;
        }
    }

    //  Partial row?
    if ($tdctr != 2) print '</tr>' . PHP_EOL ;
?>
                </tbody>
                </table>
            </div>
        <div><h3><a href="#">Left Header Image</a></h3>
            <?php casl_header_image_drag_n_drop("lft") ; ?>
        </div>
        <div><h3><a href="#">Center Header Image</a></h3>
            <?php casl_header_image_drag_n_drop("ctr") ; ?>
        </div>
        <div><h3><a href="#">Right Header Image</a></h3>
            <?php casl_header_image_drag_n_drop("rght") ; ?>
        </div>
        <div><h3><a href="#">Inline CSS Overrides</a></h3>
            <div>
                <table>
                <tr>
                <td>
                <h4 style="margin: 0.6em 0 0.3em 0;">Blog Title</h4>
                <input size="60" type="text" name="<?php echo 'casl_theme_options[' . CASL_THEME_OPTION_BLOG_TITLE_CSS . ']'; ?>" value="<?php echo $theme_options[CASL_THEME_OPTION_BLOG_TITLE_CSS] ?>"/>
                </td>
                <td style="padding-left: 2.0em;">
                <h4 style="margin: 0.6em 0 0.3em 0;">Blog Tagline</h4>
                <input size="60" type="text" name="<?php echo 'casl_theme_options[' . CASL_THEME_OPTION_BLOG_TAGLINE_CSS . ']'; ?>" value="<?php echo $theme_options[CASL_THEME_OPTION_BLOG_TAGLINE_CSS] ?>"/>
                </td>
                </tr>
                <tr>
                <td>
                <h4 style="margin: 0.6em 0 0.3em 0;">Branding Block</h4>
                <input size="60" type="text" name="<?php echo 'casl_theme_options[' . CASL_THEME_OPTION_BRANDING_DIV_CSS . ']'; ?>" value="<?php echo $theme_options[CASL_THEME_OPTION_BRANDING_DIV_CSS] ?>"/>
                </td>
                <td style="padding-left: 2.0em;">
                <h4 style="margin: 0.6em 0 0.3em 0;">Header Image Block</h4>
                <input size="60" type="text" name="<?php echo 'casl_theme_options[' . CASL_THEME_OPTION_HDR_DIV_CSS. ']'; ?>" value="<?php echo $theme_options[CASL_THEME_OPTION_HDR_DIV_CSS] ?>"/>
                </td>
                </tr>
                <tr>
                <td>
                <h4 style="margin: 0.6em 0 0.3em 0;">CASL League Logo Image Block</h4>
                <input size="60" type="text" name="<?php echo 'casl_theme_options[' . CASL_THEME_OPTION_LLI_DIV_CSS. ']'; ?>" value="<?php echo $theme_options[CASL_THEME_OPTION_LLI_DIV_CSS] ?>"/>
                </td>
                <td style="padding-left: 2.0em;">
                <h4 style="margin: 0.6em 0 0.3em 0;">CASL League Logo Image</h4>
                <input size="60" type="text" name="<?php echo 'casl_theme_options[' . CASL_THEME_OPTION_LLI_IMG_CSS. ']'; ?>" value="<?php echo $theme_options[CASL_THEME_OPTION_LLI_IMG_CSS] ?>"/>
                </td>
                </tr>
                <tr>
                <td>
                <h4 style="margin: 0.6em 0 0.3em 0;">Left Header Image Block</h4>
                <input size="60" type="text" name="<?php echo 'casl_theme_options[' . CASL_THEME_OPTION_HIL_DIV_CSS. ']'; ?>" value="<?php echo $theme_options[CASL_THEME_OPTION_HIL_DIV_CSS] ?>"/>
                </td>
                <td style="padding-left: 2.0em;">
                <h4 style="margin: 0.6em 0 0.3em 0;">Left Header Image</h4>
                <input size="60" type="text" name="<?php echo 'casl_theme_options[' . CASL_THEME_OPTION_HIL_IMG_CSS. ']'; ?>" value="<?php echo $theme_options[CASL_THEME_OPTION_HIL_IMG_CSS] ?>"/>
                </td>
                </tr>
                <tr>
                <td>
                <h4 style="margin: 0.6em 0 0.3em 0;">Center Header Image Block</h4>
                <input size="60" type="text" name="<?php echo 'casl_theme_options[' . CASL_THEME_OPTION_HIC_DIV_CSS. ']'; ?>" value="<?php echo $theme_options[CASL_THEME_OPTION_HIC_DIV_CSS] ?>"/>
                </td>
                <td style="padding-left: 2.0em;">
                <h4 style="margin: 0.6em 0 0.3em 0;">Center Header Image</h4>
                <input size="60" type="text" name="<?php echo 'casl_theme_options[' . CASL_THEME_OPTION_HIC_IMG_CSS. ']'; ?>" value="<?php echo $theme_options[CASL_THEME_OPTION_HIC_IMG_CSS] ?>"/>
                </td>
                </tr>
                <tr>
                <td>
                <h4 style="margin: 0.6em 0 0.3em 0;">Right Header Image Block</h4>
                <input size="60" type="text" name="<?php echo 'casl_theme_options[' . CASL_THEME_OPTION_HIR_DIV_CSS. ']'; ?>" value="<?php echo $theme_options[CASL_THEME_OPTION_HIR_DIV_CSS] ?>"/>
                </td>
                <td style="padding-left: 2.0em;">
                <h4 style="margin: 0.6em 0 0.3em 0;">Right Header Image</h4>
                <input size="60" type="text" name="<?php echo 'casl_theme_options[' . CASL_THEME_OPTION_HIR_IMG_CSS. ']'; ?>" value="<?php echo $theme_options[CASL_THEME_OPTION_HIR_IMG_CSS] ?>"/>
                </td>
                </tr>
                </table>
            </div>
        </div>
        </div>
        <input type="hidden" name="casl_theme_options[casllfthdrimg]" value="<?php echo $theme_options[CASL_THEME_OPTION_HIL]; ?>" />
        <input type="hidden" name="casl_theme_options[caslctrhdrimg]" value="<?php echo $theme_options[CASL_THEME_OPTION_HIC]; ?>" />
        <input type="hidden" name="casl_theme_options[caslrghthdrimg]" value="<?php echo $theme_options[CASL_THEME_OPTION_HIR]; ?>" />
        <input type="hidden" name="casl_theme_options[caslthmbsclfctr]" value="<?php echo $theme_options[CASL_THEME_OPTION_THUMBNAIL_SCALE_FACTOR]; ?>" />
        <?php submit_button(); ?>
        </div><!-- options-accordion -->
    </form>

<script type="text/javascript">

//
//  This jQuery/jQuery UI code was derived from the
//  jQuery UI Simple Photo Manager Example found at:
//
//  http://jqueryui.com/demos/droppable/#photo-manager
//
//  This Javascript allows the user to select images from
//  the media library to be used in the thene header using
//  a drag and drop implementation.
//
//  This script cannot be loaded as a separate Javascript
//  file because parts of it are derived on the fly as
//  part of the server side PHP process.
//

jQuery(document).ready(function($) {
    //  Set up the accordion and set the first section to be open
    $("#options-accordion").accordion({header: "h3", active: 0, autoHeight: true});

    // set up the left header image gallery and container
    var $casllfthdrcntr = false ;
    var $casllfthdrimg = $('#casllfthdrimg');
    var $casllfthdrgallery = $('#casllfthdrgallery');

    // set up the center header image gallery and container
    var $caslctrhdrcntr = false ;
    var $caslctrhdrimg = $('#caslctrhdrimg');
    var $caslctrhdrgallery = $('#caslctrhdrgallery');

    // set up the right header image gallery and container
    var $caslrghthdrcntr = false ;
    var $caslrghthdrimg = $('#caslrghthdrimg');
    var $caslrghthdrgallery = $('#caslrghthdrgallery');

    // let the left header gallery items be draggable
    $('li',$casllfthdrgallery).draggable({
        cancel: 'a.ui-icon',// clicking an icon won't initiate dragging
        revert: 'invalid', // when not dropped, the item will revert back to its initial position
        containment: $('#demo-frame').length ? '#demo-frame' : 'document', // stick to demo-frame if present
        helper: 'clone',
        cursor: 'move'
    });

    // let the left header image be droppable, accepting the gallery items
    $casllfthdrimg.droppable({
        accept: '#casllfthdrgallery > li',
        activeClass: 'ui-state-highlight',
        drop: function(ev, ui) {
            selectImage(ui.draggable, ui.draggable.attr('id'));
        }
    });

    // let the left gallery be droppable as well,
    // accepting items from the left header image
    $casllfthdrgallery.droppable({
        accept: '#casllfthdrimg li',
        activeClass: 'custom-state-active',
        drop: function(ev, ui) {
            removeImage(ui.draggable, ui.draggable.attr('id'));
        }
    });

    // let the center header gallery items be draggable
    $('li',$caslctrhdrgallery).draggable({
        cancel: 'a.ui-icon',// clicking an icon won't initiate dragging
        revert: 'invalid', // when not dropped, the item will revert back to its initial position
        containment: $('#demo-frame').length ? '#demo-frame' : 'document', // stick to demo-frame if present
        helper: 'clone',
        cursor: 'move'
        });

    // let the center header image be droppable,
    // accepting the gallery items
    $caslctrhdrimg.droppable({
        accept: '#caslctrhdrgallery > li',
        activeClass: 'ui-state-highlight',
        drop: function(ev, ui) {
            selectImage(ui.draggable, ui.draggable.attr('id'));
        }
    });

    // let the center gallery be droppable as well,
    // accepting items from the left header image
    $caslctrhdrgallery.droppable({
        accept: '#caslctrhdrimg li',
        activeClass: 'custom-state-active',
        drop: function(ev, ui) {
            removeImage(ui.draggable);
        }
    });

    // let the center header gallery items be draggable
    $('li',$caslrghthdrgallery).draggable({
        cancel: 'a.ui-icon',// clicking an icon won't initiate dragging
        revert: 'invalid', // when not dropped, the item will revert back to its initial position
        containment: $('#demo-frame').length ? '#demo-frame' : 'document', // stick to demo-frame if present
        helper: 'clone',
        cursor: 'move'
    });

    // let the right header image be droppable,
    // accepting the gallery items
    $caslrghthdrimg.droppable({
        accept: '#caslrghthdrgallery > li',
        activeClass: 'ui-state-highlight',
        drop: function(ev, ui) {
            selectImage(ui.draggable, ui.draggable.attr('id'));
        }
    });

    // let the right gallery be droppable as well,
    // accepting items from the left header image
    $caslrghthdrgallery.droppable({
        accept: '#caslrghthdrimg li',
        activeClass: 'custom-state-active',
        drop: function(ev, ui) {
            removeImage(ui.draggable);
        }
    });

    // image deletion function
    var recycle_icon = '<a href="#" title="Remove Image" class="ui-icon ui-icon-trash">Remove Image</a>';

    function selectImage($item, $attrid) {
        var inputName;
        // Find numeric id of header image
        var imageId = $attrid.replace(/[^0-9]/gi,'')/1;
        var galleryId = $attrid.split("-", 2)[0];

        var hdrimg = null;

        switch (galleryId)
        {
            case "casllfthdrimg" :
                hdrimg = $casllfthdrimg;
                break;
 
            case "caslctrhdrimg" :
                hdrimg = $caslctrhdrimg;
                break;
 
            case "caslrghthdrimg" :
                hdrimg = $caslrghthdrimg;
                break;
        }
 
        $item.fadeOut(function() {
            var $list = $('ul',hdrimg).length ? $('ul',hdrimg) : $('<ul class="gallery ui-helper-reset"/>').appendTo(hdrimg);

            $item.find('a.ui-icon-check').remove();
            $item.append(recycle_icon).appendTo($list).fadeIn(function() {
                $item.animate({ width: '<?php echo $thumbnail_width . "px" ?>' }).find('img').animate({ height: '<?php echo $thumbnail_height . "px" ?>' });
        return ;
            });
        });

        hdrimg.droppable('disable');

        switch (galleryId)
        {
            case "casllfthdrimg" :
                $casllfthdrcntr = true ;
                break;
 
            case "caslctrhdrimg" :
                $caslctrhdrcntr = true;
                break;
 
            case "caslrghthdrimg" :
                $caslrghthdrcntr = true;
                break;
        }
 
        inputName='casl_theme_options[' + galleryId + ']';
        $("input[name='" + inputName + "']").val(imageId);
    }

    // image recycle function
    var trash_icon = '<a href="#" title="Select Image" class="ui-icon ui-icon-check">Select Image</a>';
    function removeImage($item, $attrid) {
        var inputName;
        // Find numeric id of header image
        var imageId = $attrid.replace(/[^0-9]/gi,'')/1;
        var galleryId = $attrid.split("-", 2)[0];

        var hdrimg = null;
        var hdrgallery = null;

        switch (galleryId)
        {
            case "casllfthdrimg" :
                hdrimg = $casllfthdrimg;
                hdrgallery = $casllfthdrgallery;
                break;
 
            case "caslctrhdrimg" :
                hdrimg = $caslctrhdrimg;
                hdrgallery = $caslctrhdrgallery;
                break;
 
            case "caslrghthdrimg" :
                hdrimg = $caslrghthdrimg;
                hdrgallery = $caslrghthdrgallery;
                break;
        }
 
        $item.fadeOut(function() {
            $item.find('a.ui-icon-trash').remove();
            $item.css('width','<?php echo $thumbnail_width . "px" ?>').append(trash_icon).find('img').css('height','<?php echo $thumbnail_height . "px" ?>').end().appendTo(hdrgallery).fadeIn();
        });

        hdrimg.droppable('enable');

        switch (galleryId)
        {
            case "casllfthdrimg" :
                $casllfthdrcntr = false;
                break;
 
            case "caslctrhdrimg" :
                $caslctrhdrcntr = false;
                break;
 
            case "caslrghthdrimg" :
                $caslrghthdrcntr = false;
                break;
        }
 
        inputName='casl_theme_options[' + galleryId + ']';
        $("input[name='" + inputName + "']").val("");
    }

    // image preview function, demonstrating the ui.dialog used as a modal window
    function viewLargerImage($link) {
        var src = $link.attr('href');
        var title = $link.siblings('img').attr('alt');
        var $modal = $('img[src$="'+src+'"]');

        //  Note sure why this first part of the IF block isn't work nor what it
        //  really does.  Commenting it out seems to make it work though!  2011-09-17

        if (!$modal.length) {
            $modal.dialog('open')
        } else {
            var img = $('<img alt="'+title+'" width="800" height="600" style="display:none;padding: 8px;" />').attr('src',src).appendTo('body');
            setTimeout(function() {
                img.dialog({
                    title: title,
                    width: 400,
                    modal: true
                });
            }, 1);
        }
    }

    // resolve the icons behavior with event delegation
    $('ul.gallery > li').click(function(ev) {
        var $item = $(this);
        var $target = $(ev.target);

        var hdrcntr = null;
        var gallery = $item.attr('id').split("-", 2)[0];

        switch (gallery)
        {
            case "casllfthdrimg" :
                hdrcntr = $casllfthdrcntr;
                hdrgallery = $casllfthdrgallery;
                break;
 
            case "caslctrhdrimg" :
                hdrcntr = $caslctrhdrcntr;
                hdrgallery = $caslctrhdrgallery;
                break;
 
            case "caslrghthdrimg" :
                hdrcntr = $caslrghthdrcntr;
                hdrgallery = $caslrghthdrgallery;
                break;
        }

        if ($target.is('a.ui-icon-check')) {
            if (hdrcntr) {
                $item.fadeOut('slow', function() {
                    $item.appendTo(hdrgallery);
                }) ;
                $item.fadeIn('slow') ;
            }
            else {
                selectImage($item, $item.attr('id'));
            }
        } else if ($target.is('a.ui-icon-zoomin')) {
            viewLargerImage($target);
        } else if ($target.is('a.ui-icon-trash')) {
            removeImage($item, $item.attr('id'));
        }

        return false;
    });


    //  Preload header images?  Need to move any images
    //  that are already set as one of the header images.
 

    //  Left header image preload?
    if ($("input[name='casl_theme_options[casllfthdrimg]']").val() != "") {
        selectImage($("#casllfthdrimg-" +
            $("input[name='casl_theme_options[casllfthdrimg]']").val()), "casllfthdrimg-" +
            $("input[name='casl_theme_options[casllfthdrimg]']").val()) ;
    }

    //  Center header image preload?
    if ($("input[name='casl_theme_options[caslctrhdrimg]']").val() != "") {
        selectImage($("#caslctrhdrimg-" +
            $("input[name='casl_theme_options[caslctrhdrimg]']").val()), "caslctrhdrimg-" +
            $("input[name='casl_theme_options[caslctrhdrimg]']").val()) ;
    }

    //  Right header image preload?
    if ($("input[name='casl_theme_options[caslrghthdrimg]']").val() != "") {
        selectImage($("#caslrghthdrimg-" +
            $("input[name='casl_theme_options[caslrghthdrimg]']").val()), "caslrghthdrimg-" +
            $("input[name='casl_theme_options[caslrghthdrimg]']").val()) ;
    }
});
</script>    

<?php
}

function casl_theme_options_validate($input)
{
    return $input ;
}
?>
